package com.stars.easyms.datasource.pointcut;

import java.lang.annotation.Annotation;
import java.lang.reflect.Proxy;
import java.util.List;

import com.stars.easyms.base.pointcut.EasyMsAnnotationClassFilter;
import com.stars.easyms.base.util.AnnotationUtil;
import com.stars.easyms.datasource.common.EasyMsDataSourceConstant;
import com.stars.easyms.datasource.mybatisplus.EasyMsMybatisPlusHelper;
import org.springframework.lang.NonNull;

/**
 * <p>className: EasyMsDataSourceAnnotationClassFilter</p>
 * <p>description: EasyMs注解类过滤器</p>
 *
 * @author guoguifang
 * @version 1.2.1
 * @date 2019/5/10 12:25
 */
class EasyMsDataSourceAnnotationClassFilter extends EasyMsAnnotationClassFilter {

    EasyMsDataSourceAnnotationClassFilter(List<Class<? extends Annotation>> annotationTypeList) {
        super(annotationTypeList, true);
    }

    @Override
    public boolean matches(@NonNull Class<?> clazz) {
        if (Proxy.isProxyClass(clazz)) {
            // 如果是mybatis的代理类则获取其父接口类判断
            Class<?>[] interfaceClasses = clazz.getInterfaces();
            if (interfaceClasses != null && interfaceClasses.length > 0) {
                for (Class<?> interfaceClass : interfaceClasses) {
                    if (isMatches(interfaceClass)) {
                        return true;
                    }
                }
            }
        }
        return isMatches(clazz);
    }

    private boolean isMatches(@NonNull Class<?> clazz) {
        for (Class<? extends Annotation> annotationType : getAnnotationTypeList()) {
            boolean isMatch = isCheckInherited() ? AnnotationUtil.hasAnnotation(clazz, annotationType) : clazz.isAnnotationPresent(annotationType);
            if (!isMatch && EasyMsDataSourceConstant.SUPPORT_ANNOTATION_TYPE_LIST.contains(annotationType)) {
                isMatch = EasyMsMybatisPlusHelper.isMybatisPlusMapper(clazz);
            }
            if (isMatch) {
                return true;
            }
        }
        return false;
    }

}
